package server

import (
	"io"
	"log"
	"os"
)

type UploadSeverImpl struct{}

func (u *UploadSeverImpl) Upload(server Upload_UploadServer) error {
	for {
		//循环接收客户端传递的流数据
		recv, err := server.Recv()
		if recv != nil {
			writeContet(recv.Path, recv.Data)
		}
		//检测EOF
		if err == io.EOF {
			err := server.SendAndClose(&UploadRes{Msg: "finish"})
			if err != nil {
				return err
			}
			return nil
		} else if err != nil {
			return err
		}

		log.Printf("get a upload data package~offset: %v, size: %v", recv.Offset, recv.Size)
	}
}
func writeContet(filename string, c []byte) error {
	file, err := os.OpenFile(filename, os.O_APPEND, 0666)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = file.Write(c)
	if err != nil {
		return err
	}
	return nil
}
